
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="Django 用户认证（Auth）组件">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>Django 用户认证（Auth）组件 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Django 用户认证（Auth）组件
      </h1>
      <span>
        
        <time class="time" datetime="2019-12-08T16:00:00.000Z">
        2019-12-09
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h3 id="Django-用户认证（Auth）组件"><a href="#Django-用户认证（Auth）组件" class="headerlink" title="Django 用户认证（Auth）组件"></a>Django 用户认证（Auth）组件</h3><p>Django 用户认证（Auth）组件一般用在用户的登录注册上，用于判断当前的用户是否合法，并跳转到登陆成功或失败页面。</p>
<p>Django 用户认证（Auth）组件需要导入 auth 模块:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># 认证模块</span><br><span class="line">from django.contrib import auth</span><br><span class="line"></span><br><span class="line"># 对应数据库</span><br><span class="line">from django.contrib.auth.models import User</span><br></pre></td></tr></table></figure>

<p>返回值是用户对象。</p>
<h4 id="创建用户的三种方式"><a href="#创建用户的三种方式" class="headerlink" title="创建用户的三种方式"></a>创建用户的三种方式</h4><p>创建用户对象的三种方法：</p>
<ul>
<li><strong>create()</strong>：创建一个普通用户，密码是明文的。</li>
<li><strong>create_user()</strong>：创建一个普通用户，密码是密文的。</li>
<li><strong>create_superuser()</strong>：创建一个超级用户，密码是密文的，要多传一个邮箱 email 参数。</li>
</ul>
<p><strong>参数：</strong></p>
<ul>
<li>username: 用户名。</li>
<li>password：密码。</li>
<li>email：邮箱 (create_superuser 方法要多加一个 email)。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.models import User </span><br><span class="line">User.objects.create(username=&apos;runboo&apos;,password=&apos;123&apos;)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-auth_1.gif" alt="img"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.models import User </span><br><span class="line">User.objects.create_user(username=&apos;runbooo&apos;,password=&apos;123&apos;)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-auth_2.gif" alt="img"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.models import User </span><br><span class="line">User.objects.create_superuser(username=&apos;runboooo&apos;,password=&apos;123&apos;,email=&apos;runboo@163.com&apos;)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-auth_3.gif" alt="img"></p>
<h4 id="验证用户"><a href="#验证用户" class="headerlink" title="验证用户"></a>验证用户</h4><p>验证用户的用户名和密码使用 authenticate() 方法，从 auth_user 表中过滤出用户对象。</p>
<p>使用前要导入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib import auth</span><br></pre></td></tr></table></figure>

<p>参数：</p>
<ul>
<li>username：用户名</li>
<li>password：密码</li>
</ul>
<p><strong>返回值：</strong>如果验证成功，就返回用户对象，反之，返回 None。</p>
<p>例子</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"GET"</span>:</span><br><span class="line">      <span class="keyword">return</span> render(request, <span class="string">"login.html"</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      username = request.POST.get(<span class="string">"username"</span>)</span><br><span class="line">      password = request.POST.get(<span class="string">"pwd"</span>)</span><br><span class="line">      user_obj = auth.authenticate(username=username, password=password)</span><br><span class="line">      print(user_obj.username)</span><br></pre></td></tr></table></figure>

<p>给验证成功的用户加 session，将 request.user 赋值为用户对象。</p>
<p>登陆使用 login() 方法。</p>
<p>使用前要导入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib import auth</span><br></pre></td></tr></table></figure>

<p>参数：</p>
<ul>
<li>request：用户对象</li>
</ul>
<p>返回值：None</p>
<p>例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"GET"</span>:</span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"login.html"</span>)</span><br><span class="line">      </span><br><span class="line">    username = request.POST.get(<span class="string">"username"</span>)</span><br><span class="line">    password = request.POST.get(<span class="string">"pwd"</span>)</span><br><span class="line">    </span><br><span class="line">    user_obj = auth.authenticate(username=username, password=password)</span><br><span class="line">    print(user_obj.username)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> user_obj:</span><br><span class="line">      <span class="keyword">return</span> redirect(<span class="string">"/login/"</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      auth.login(request, user_obj)</span><br><span class="line">      path = request.GET.get(<span class="string">"next"</span>) <span class="keyword">or</span> <span class="string">"/index/"</span></span><br><span class="line">      print(path)</span><br><span class="line">      <span class="keyword">return</span> redirect(path)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-auth_1.png" alt="img"></p>
<h4 id="登出"><a href="#登出" class="headerlink" title="登出"></a>登出</h4><p>注销用户使用 logout() 方法，需要清空 session 信息，将 request.user 赋值为匿名用户。</p>
<p>使用前要导入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib import auth</span><br></pre></td></tr></table></figure>

<p>参数：</p>
<ul>
<li>request：用户对象</li>
</ul>
<p>返回值：None</p>
<p>例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">logout</span><span class="params">(request)</span>:</span> </span><br><span class="line">  ppp = auth.logout(request) </span><br><span class="line">  print(ppp) <span class="comment"># None </span></span><br><span class="line">  <span class="keyword">return</span> redirect(<span class="string">"/login/"</span>)</span><br></pre></td></tr></table></figure>

<h4 id="设置装饰器登录"><a href="#设置装饰器登录" class="headerlink" title="设置装饰器登录"></a>设置装饰器登录</h4><p>设置装饰器，给需要登录成功后才能访问的页面统一加装饰器。</p>
<p>使用前要导入：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib.auth.decorators <span class="keyword">import</span> login_required</span><br><span class="line"><span class="meta">@login_required </span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span> </span><br><span class="line">  <span class="keyword">return</span> HttpResponse(<span class="string">"index页面。。。"</span>)</span><br></pre></td></tr></table></figure>


    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Django-用户认证（Auth）组件"><span class="toc-text">Django 用户认证（Auth）组件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#创建用户的三种方式"><span class="toc-text">创建用户的三种方式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#验证用户"><span class="toc-text">验证用户</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#登出"><span class="toc-text">登出</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#设置装饰器登录"><span class="toc-text">设置装饰器登录</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2019/12/08/Django的中间件/" rel="next" title="Django中间件">
          Django中间件
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2019/12/09/gopsutil的使用/" rel="prev" title="gopsutil获取服务器的信息">
            gopsutil获取服务器的信息
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
